#!/usr/bin/python
# -*- coding: utf-8 -*-

import functools
import os
import sys
import traceback

from flask import g, flash, redirect, url_for, make_response
import json

import rest_exceptions


def log_request(f):
    @functools.wraps(f)
    def decorated(*args, **kwargs):
        g.log_info['func_name'] = f.func_name
        g.log_info['args'] = [str(a) for a in args]
        g.log_info['pid'] = os.getpid()
        if kwargs:
            g.log_info['kwargs'] = kwargs
        try:
            ret = f(*args, **kwargs)
            g.log_info['ret'] = ret
        except:
            e = sys.exc_info()[0]
            g.log_info['exception'] = str(e)
            g.log_info['format_exc'] = traceback.format_exc()
            g.log_info['ret'] = str(e)
            raise
        return ret
    return decorated


def verify_logined(app):
    @app.before_request
    def login_required():
        if not(hasattr(g, 'logined') and g.logined is True):
            flash(u'请先登录', 'warning')
            return redirect(url_for("user_login"))
    return app


def return_json(f):
    @functools.wraps(f)
    def decorated(*args, **kwargs):
        try:
            ret = f(*args, **kwargs)
        except rest_exceptions.RESTError as e:
            ret = (e.to_dict(), e.status_code)

        if isinstance(ret, tuple):
            ret = list(ret)
        else:
            ret = [ret]
        ret[0] = json.dumps(ret[0])

        json_ret = make_response(tuple(ret))
        json_ret.mimetype = 'application/json'
        return json_ret
    return decorated
